// 云函数入口文件
const cloud = require('wx-server-sdk')
var request = require('request')

cloud.init({
    env:'tfjkp-0ge80vu9ea710148'
})

const db = cloud.database()
const _ = db.command
const serverInfo = db.collection("shopInfo") //存储可以兑换的商品信息表
const userInfo = db.collection('userInfo'); //用户信息表


// 云函数入口函数
exports.main = async (event, context) => {
  let { OPENID, APPID, UNIONID } = await cloud.getWXContext()

    if(event.type == "shop"){
        return new Promise((resolve, reject) => {
            // setTimeout(() => {
                serverInfo
                .get()
                .then(res => {
                    resolve(res)
                })
            // }, 3000)
          })
    }else if(event.type == "checkEneray"){
        return new Promise((resolve, reject) => {
          
            userInfo.where({openid:OPENID}).get().then(res => {
                resolve(res.data[0]._eneray)  
            })
      })
    } else if(event.type == "exchangeOrder"){
        try{
            const result = await db.runTransaction(async transaction => {
                const shopInfo = await transaction.collection('shopInfo').doc(event.commodityId).get();
                console.log(shopInfo)
                if(shopInfo.data){
                    if(shopInfo.data._quantity >= 1){
                        const updateShopInfo = await transaction.collection('shopInfo').doc(event.commodityId).update({
                            data:{
                                _quantity:_.inc(-1)
                            }
                        })
                        const updateUserEneray = await transaction.collection('userInfo').where({openid:OPENID}).update({
                            data:{
                                _eneray:_.inc(-event.price)
                            }
                        })
    
                        return {
                            theShopInfo: shopInfo.data._quantity - 1
                        }
                    }else{
                       const updateShopInfo4Type = await transaction.collection('shopInfo').doc(event.commodityId).update({
                           data:{
                               '_commodityId._type':"已售罄"
                           }
                       })
                        return {
                            theShopInfo: "已售罄"
                        }
                    }
 
                }else {
                    await transaction.rollback(-100)
                }

                
            })
            
            console.log('transaction success', result);

            return {
                success: true,
                theShopInfo: result.theShopInfo
            }

           
        }catch(e){
            console.error('transacation error',e)

            return {
                success: false,
                error: e
            }
        }

    }else if(event.type == "orderRequest"){
        var orderInfo = {
            "stuId":event.orderInfo.stuId,
            "stuName":event.orderInfo.stuName,
            "shopName":event.orderInfo.shopName,
            "shopId":event.orderInfo.shopId,
            "shopGd":event.orderInfo.shopGd,
            "userGd":"",
            "extraString": event.orderInfo.shopType
        }
        console.log(orderInfo)
        return new Promise((resolve, reject) => {
        
            userInfo.where({openid:OPENID}).get().then(res => {
                orderInfo.userGd = (res.data[0]._eneray)
                request({
                    url: event.url,
                    method: "POST",
                    json: true,
                    headers: {
                      "content-type": "application/json",
                  
                    },
                    body: orderInfo
                  }, function (error, response, body) {  
                    console.log(body)         
                    if (!error && response.statusCode == 200) {
                      try {
                        resolve(body)
                      } catch (e) {
                        reject()
                      }
                    }
                  })
            })

          })
    }else if(event.type == "checkOrderIs"){
        var orderInfo = {
            "stuId": event.stuId,
            "orderId": event.orderId
        }
        return new Promise((resolve, reject) => {
        request({
            url: event.url,
            method: "POST",
            json: true,
            headers: {
              "content-type": "application/json",
          
            },
            body: orderInfo
          }, function (error, response, body) {  
            console.log(body)         
            if (!error && response.statusCode == 200) {
              try {
                resolve(body)
              } catch (e) {
                reject()
              }
            }
          })
     })
    }else if(event.type == "getEnerayRank"){
        return new Promise((resolve, reject) => {

            userInfo.field({
                _eneray:true,
                _avatarUrl:true,
                _nickName:true,
                _motionTime:true
            }).orderBy("_eneray","desc").get().then(res => {
                var newArr = res.data.slice(0,60)
                if(newArr[0]._eneray > 0){
                  var lstLen = newArr.length -1;
                  if(newArr[lstLen]._eneray > 0){
                    resolve(newArr)
                  }else{
                    for(var i = 0; i < newArr.length; i++){
                      if(newArr[i]._eneray == 0){
                          var newArr2 = newArr.slice(0,i-1)  
                          resolve(newArr2)
                        }                
                    }
                  }

                }else{
                    resolve(newArr)
                }
                })
          })
    }else if(event.type == "getUserOrderInfo"){
        return new Promise((resolve, reject) => {
            var getOrderInfo = {
                "stuId":event.body.stuId
            }
            console.log(getOrderInfo)
            request({
                url: event.url,
                method: "POST",
                json: true,
                headers: {
                  "content-type": "application/json",
              
                },
                body:getOrderInfo
              }, function (error, response, body) {  
                console.log(body)         
                if (!error && response.statusCode == 200) {
                  try {
                    resolve(body)
                  } catch (e) {
                    reject()
                  }
                }
              })
            })
    }else if(event.type == "getImsList"){
      return new Promise((resolve, reject) => {
          var getOrderInfo = {
              "stuId":event.body.stuId
          }
          console.log(getOrderInfo)
          request({
              url: event.url,
              method: "POST",
              json: true,
              headers: {
                "content-type": "application/json",
            
              },
              body:getOrderInfo
            }, function (error, response, body) {  
              console.log(body)         
              if (!error && response.statusCode == 200) {
                try {
                  resolve(body)
                } catch (e) {
                  reject()
                }
              }
            })
          })
  }
//   else if(event.type == "getPageRanking"){
//     return new Promise((resolve, reject) => {
//         var pageSkip = event.skip;
//         userInfo.field({
//             _eneray:true,
//             _avatarUrl:true,
//             _nickName:true,
//             _motionTime:true
//         }).orderBy("_eneray","desc"). skip(pageSkip)
//         .limit(10)
//         .get({
//           success: res => {
//             console.log(res)
//             // if(newArr[0]._eneray > 0){
//             //   for(var i = 0; i < newArr.length; i++){
//             //       if(newArr[i]._eneray == 0){
//             //           var newArr2 = newArr.slice(0,i-1)      
//             //           resolve(newArr2)
//             //         }                
//             //   }
//             //   }else{
//             //       resolve(newArr)
//             //   }
//           },
//           fail: err => {
//             console.log('[数据库] [查询记录] 失败：');
//           }
//         })

//       })
// }
    
}